import React, { useState, useEffect } from 'react';
import api from '../../services/api';
import './AdminPostManagement.css';

function AdminPostManagement({ user, token }) {
    const [posts, setPosts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [message, setMessage] = useState({ type: '', text: '' });
    const [operationLoading, setOperationLoading] = useState({});
    const [confirmDialog, setConfirmDialog] = useState({
        show: false,
        type: '',
        postId: null,
        postTitle: ''
    });

    // Token 提取逻辑
    const actualToken = (() => {
        let extractedToken = null;

        if (token && token !== 'undefined' && token !== 'null' && token.trim() !== '') {
            extractedToken = token.trim();
        } else if (user?.data?.token) {
            extractedToken = user.data.token.trim();
        }

        if (extractedToken) {
            const parts = extractedToken.split('.');
            if (parts.length !== 3) {
                console.error('Token 格式不正确');
                return null;
            }
            return extractedToken;
        }

        return null;
    })();

    useEffect(() => {
        if (actualToken) {
            fetchAllPosts();
        } else {
            setMessage({ type: 'error', text: '缺少认证信息，请重新登录' });
            setLoading(false);
        }
    }, [actualToken]);

    // 获取所有帖子
    const fetchAllPosts = async () => {
        try {
            setLoading(true);
            const result = await api.getAdminAllPosts(actualToken);

            // 处理可能的数据结构
            const postsData = result.data || result;
            if (Array.isArray(postsData)) {
                setPosts(postsData);
            } else {
                console.error('返回的数据不是数组:', postsData);
                setPosts([]);
            }

            setMessage({ type: 'success', text: '帖子列表加载成功' });
        } catch (error) {
            console.error('获取帖子列表失败:', error);
            setMessage({ type: 'error', text: error.message || '获取帖子列表失败' });
            setPosts([]);
        } finally {
            setLoading(false);
        }
    };

    // 显示确认对话框
    const showConfirmDialog = (type, postId, postTitle) => {
        setConfirmDialog({
            show: true,
            type,
            postId,
            postTitle
        });
    };

    // 隐藏确认对话框
    const hideConfirmDialog = () => {
        setConfirmDialog({
            show: false,
            type: '',
            postId: null,
            postTitle: ''
        });
    };

    // 删除帖子
    const handleDeletePost = async (postId) => {
        try {
            setOperationLoading(prev => ({ ...prev, [`delete_${postId}`]: true }));

            await api.adminDeletePost(actualToken, postId);

            // 从列表中移除已删除的帖子
            setPosts(prev => prev.filter(post => post.id !== postId));
            setMessage({ type: 'success', text: '帖子删除成功' });
            hideConfirmDialog();
        } catch (error) {
            console.error('删除帖子失败:', error);
            setMessage({ type: 'error', text: error.message || '删除帖子失败' });
        } finally {
            setOperationLoading(prev => ({ ...prev, [`delete_${postId}`]: false }));
        }
    };

    // 切换置顶状态
    const handleToggleSticky = async (postId, isSticky) => {
        try {
            setOperationLoading(prev => ({ ...prev, [`sticky_${postId}`]: true }));

            if (isSticky) {
                await api.adminUnstickyPost(actualToken, postId);
            } else {
                await api.adminStickyPost(actualToken, postId);
            }

            // 更新帖子的置顶状态
            setPosts(prev => prev.map(post =>
                post.id === postId
                    ? { ...post, isSticky: !isSticky }
                    : post
            ));

            setMessage({
                type: 'success',
                text: isSticky ? '取消置顶成功' : '设置置顶成功'
            });
            hideConfirmDialog();
        } catch (error) {
            console.error('切换置顶状态失败:', error);
            setMessage({ type: 'error', text: error.message || '操作失败' });
        } finally {
            setOperationLoading(prev => ({ ...prev, [`sticky_${postId}`]: false }));
        }
    };

    // 执行确认的操作
    const executeConfirmedAction = () => {
        const { type, postId } = confirmDialog;
        const post = posts.find(p => p.id === postId);

        if (type === 'delete') {
            handleDeletePost(postId);
        } else if (type === 'sticky') {
            handleToggleSticky(postId, post?.isSticky);
        }
    };

    // 格式化日期
    const formatDate = (dateString) => {
        return new Date(dateString).toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    // 截断文本
    const truncateText = (text, maxLength = 50) => {
        if (!text) return '';
        return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
    };

    if (loading) {
        return (
            <div className="admin-loading">
                <div className="loading-spinner"></div>
                加载中...
            </div>
        );
    }

    if (!actualToken) {
        return (
            <div className="admin-container">
                <div className="admin-card">
                    <p className="admin-error-text">请先登录后再访问管理页面</p>
                </div>
            </div>
        );
    }

    return (
        <div className="admin-container">
            <div className="admin-header">
                <div className="admin-title">
                    <h1>帖子管理</h1>
                    <p>管理所有用户发布的帖子内容</p>
                </div>
                <button
                    onClick={fetchAllPosts}
                    className="refresh-btn"
                    disabled={loading}
                >
                    🔄 刷新
                </button>
            </div>

            {message.text && (
                <div className={`admin-message ${message.type}`}>
                    {message.text}
                </div>
            )}

            <div className="admin-content">
                <div className="posts-stats">
                    <div className="stat-item">
                        <span className="stat-label">总帖子数：</span>
                        <span className="stat-value">{posts.length}</span>
                    </div>
                    <div className="stat-item">
                        <span className="stat-label">置顶帖子：</span>
                        <span className="stat-value">{posts.filter(post => post.isSticky).length}</span>
                    </div>
                </div>

                <div className="posts-table-container">
                    {posts.length === 0 ? (
                        <div className="no-posts">
                            <span>📭</span>
                            <p>暂无帖子数据</p>
                        </div>
                    ) : (
                        <table className="posts-table">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>标题</th>
                                <th>作者</th>
                                <th>发布时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            {posts.map(post => (
                                <tr key={post.id} className={post.isSticky ? 'sticky-post' : ''}>
                                    <td>{post.id}</td>
                                    <td>
                                        <div className="post-title-cell">
                                                <span className="post-title" title={post.title}>
                                                    {truncateText(post.title, 30)}
                                                </span>
                                            <span className="post-content" title={post.content}>
                                                    {truncateText(post.content, 40)}
                                                </span>
                                        </div>
                                    </td>
                                    <td>{post.username || post.authorName || '未知用户'}</td>
                                    <td>{formatDate(post.createTime || post.createdAt)}</td>
                                    <td>
                                            <span className={`status-badge ${post.isSticky ? 'sticky' : 'normal'}`}>
                                                {post.isSticky ? '📌 置顶' : '📄 普通'}
                                            </span>
                                    </td>
                                    <td>
                                        <div className="action-buttons">
                                            <button
                                                onClick={() => showConfirmDialog('sticky', post.id, post.title)}
                                                disabled={operationLoading[`sticky_${post.id}`]}
                                                className={`action-btn ${post.isSticky ? 'unsticky-btn' : 'sticky-btn'}`}
                                                title={post.isSticky ? '取消置顶' : '设置置顶'}
                                            >
                                                {operationLoading[`sticky_${post.id}`] ? '⏳' : (post.isSticky ? '📌' : '📍')}
                                            </button>
                                            <button
                                                onClick={() => showConfirmDialog('delete', post.id, post.title)}
                                                disabled={operationLoading[`delete_${post.id}`]}
                                                className="action-btn delete-btn"
                                                title="删除帖子"
                                            >
                                                {operationLoading[`delete_${post.id}`] ? '⏳' : '🗑️'}
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                            </tbody>
                        </table>
                    )}
                </div>
            </div>

            {/* 确认对话框 */}
            {confirmDialog.show && (
                <div className="confirm-overlay">
                    <div className="confirm-dialog">
                        <div className="confirm-header">
                            <h3>确认操作</h3>
                        </div>
                        <div className="confirm-content">
                            <p>
                                {confirmDialog.type === 'delete' ? (
                                    <>您确定要删除帖子 "<strong>{truncateText(confirmDialog.postTitle, 20)}</strong>" 吗？</>
                                ) : (
                                    <>您确定要{posts.find(p => p.id === confirmDialog.postId)?.isSticky ? '取消置顶' : '设置置顶'}帖子 "<strong>{truncateText(confirmDialog.postTitle, 20)}</strong>" 吗？</>
                                )}
                            </p>
                            <p className="confirm-warning">
                                {confirmDialog.type === 'delete' ? '⚠️ 此操作不可恢复！' : '📌 这将改变帖子的显示顺序'}
                            </p>
                        </div>
                        <div className="confirm-actions">
                            <button
                                onClick={hideConfirmDialog}
                                className="cancel-btn"
                            >
                                取消
                            </button>
                            <button
                                onClick={executeConfirmedAction}
                                className={`confirm-btn ${confirmDialog.type === 'delete' ? 'danger' : 'primary'}`}
                            >
                                {confirmDialog.type === 'delete' ? '删除' : '确认'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

export default AdminPostManagement;